package codehire.zsassociates.cycliclist;

class Node {
	int data;
	Node next;
	public String toString() {
		StringBuffer b = new StringBuffer();
		Node n = this;
		do {
			b.append(n.data);
			n = n.next;
		} while(n != null && n != this);
		return b.toString();
	}
}

public class UserMainCode
{
	public static Node addElement(Node n)
	{
		Node n5 = new Node();
		n5.data = 5;
		if(n == null)
			return n5;
		Node max = n;
		while(max.next.data >= max.data && max.next != n)
			max = max.next;
		if(n5.data >= max.data) {
			n5.next = max.next;
			max.next = n5;
			max = n5;
		}
		else {
			n = max;
			while(n5.data > n.next.data)
				n = n.next;
			n5.next = n.next;
			n.next = n5;
		}
		return max.next;
	}
	public static void main(String[] args) {
		Node n1 = new Node(), n2 = new Node(), n3 = new Node();
		n1.data = 2;
		n1.next = n2;
		n2.data = 6;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 2;
		n1.next = n2;
		n2.data = 3;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n2;
		n2.data = 7;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n2;
		n2.data = 2;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 3;
		n1.next = n2;
		n2.data = 2;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 7;
		n1.next = n2;
		n2.data = 6;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 5;
		n1.next = n2;
		n2.data = 6;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 5;
		n1.next = n2;
		n2.data = 5;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n2;
		n2.data = 6;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 4;
		n1.next = n2;
		n2.data = 4;
		n2.next = n1;
		System.out.println(addElement(n1));
		n1.data = 4;
		n1.next = n2;
		n2.data = 4;
		n2.next = n3;
		n3.data = 4;
		n3.next = n1;
		System.out.println(addElement(n1));
		n1.data = 5;
		n1.next = n2;
		n2.data = 5;
		n2.next = n3;
		n3.data = 5;
		n3.next = n1;
		System.out.println(addElement(n1));
		n1.data = 4;
		n1.next = n2;
		n2.data = 5;
		n2.next = n3;
		n3.data = 4;
		n3.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n2;
		n2.data = 4;
		n2.next = n3;
		n3.data = 5;
		n3.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n2;
		n2.data = 4;
		n2.next = n3;
		n3.data = 4;
		n3.next = n1;
		System.out.println(addElement(n1));
		System.out.println(addElement(null));
		n1.data = 2;
		n1.next = n1;
		System.out.println(addElement(n1));
		n1.data = 5;
		n1.next = n1;
		System.out.println(addElement(n1));
		n1.data = 6;
		n1.next = n1;
		System.out.println(addElement(n1));
	}
}
